package com.example.community.interceptor;

import com.example.community.annotation.LoginRequired;
import com.example.community.uitls.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName: LoginRequiredInterceptor
 * @Description:
 * @Author
 * @Date 2022-03-18
 * @Version 1.0
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
   @Autowired
    HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //只拦截方法
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取请求方法的方法名
            Method method = handlerMethod.getMethod();
            //查询这个方法是否带有@LoginRequired注解
            LoginRequired annotation = method.getAnnotation(LoginRequired.class);
            //如果这个方法有注解 但用户没有登录，则不能访问资源
            if (annotation!=null && hostHolder.getUser() == null){
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
